#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File: cn2en.py
@Time: 2023/02/20 23:43:34
@Description: 英文到中文翻译工具（使用腾讯云翻译API）
'''
import json
import time
from typing import Optional
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.tmt.v20180321 import tmt_client, models

from config.config import get_config
from config.log import logger


def translate(msg: str) -> str:
    """
    将英文翻译为中文
    
    Args:
        msg (str): 需要翻译的英文文本
        
    Returns:
        str: 翻译后的中文文本，如果翻译失败则返回原文
    """
    if not msg or not msg.strip():
        return msg
    
    config = get_config()
    secret_id = config['api']['tencent_secret_id']
    secret_key = config['api']['tencent_secret_key']
    
    # 检查API密钥是否配置
    if not secret_id or not secret_key:
        logger.log('ERROR', '腾讯云API密钥未配置，返回原文')
        return msg
    
    try:
        # 实例化认证对象
        cred = credential.Credential(secret_id, secret_key)
        
        # 实例化http选项
        http_profile = HttpProfile()
        http_profile.endpoint = "tmt.tencentcloudapi.com"

        # 实例化client选项
        client_profile = ClientProfile()
        client_profile.httpProfile = http_profile
        
        # 实例化翻译客户端
        client = tmt_client.TmtClient(cred, "ap-beijing", client_profile)
        
        # 创建翻译请求
        req = models.TextTranslateRequest()
        params = {
            "SourceText": msg,
            "Source": "en",
            "Target": "zh",
            "ProjectId": 0
        }
        req.from_json_string(json.dumps(params))

        # 发送翻译请求
        resp = client.TextTranslate(req)
        data = json.loads(resp.to_json_string())['TargetText']
        
        # 防止API限流，添加延时
        time.sleep(0.3)
        
        logger.log('INFOR', f'翻译成功: {msg[:50]}... -> {data[:50]}...')
        return data

    except TencentCloudSDKException as err:
        logger.log('ERROR', f'腾讯云API调用失败: {err}')
        return msg
    except json.JSONDecodeError as err:
        logger.log('ERROR', f'JSON解析失败: {err}')
        return msg
    except Exception as err:
        logger.log('ERROR', f'翻译过程中发生未知错误: {err}')
        return msg


def batch_translate(messages: list) -> dict:
    """
    批量翻译文本
    
    Args:
        messages (list): 需要翻译的文本列表
        
    Returns:
        dict: 翻译结果字典，键为原文，值为译文
    """
    results = {}
    total = len(messages)
    
    logger.log('INFOR', f'开始批量翻译，共{total}条')
    
    for i, msg in enumerate(messages, 1):
        results[msg] = translate(msg)
        logger.log('INFOR', f'翻译进度: {i}/{total}')
        
        # 每10条增加额外延时，避免API限制
        if i % 10 == 0:
            time.sleep(1)
    
    logger.log('INFOR', f'批量翻译完成，成功翻译{len(results)}条')
    return results


# 示例用法
if __name__ == '__main__':
    test_text = 'CandidATS 3.0.0 contains a cross-site scripting vulnerability'
    result = translate(test_text)
    print(f'原文: {test_text}')
    print(f'译文: {result}')